package com.gdkj.util;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

@Slf4j
public class DingDingUtils {

    private static final String DING_DING_TALK_URL = "https://oapi.dingtalk.com/robot/send?access_token=";
    /**
     * 钉钉机器人消息文本格式
     */
    private static final String DING_DING_TALK_MSG_TYPE = "text";

    /**
     * 发送钉钉消息
     *
     * @param isAtAll     是否全员通知 true 全员通知
     * @param accessToken 钉钉token
     * @param message     消息内容
     * @param mobiles     指定通知
     * @throws Exception
     */
    public static void executeSendMessage(Boolean isAtAll, String accessToken, String message, String mobiles) throws Exception {
        // 客户端注册
        String dingDingTalkUrl = DING_DING_TALK_URL + accessToken;
        DingTalkClient client = new DefaultDingTalkClient(dingDingTalkUrl);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        // 属性设置
        request.setMsgtype(DING_DING_TALK_MSG_TYPE);
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(message);
        request.setText(text);
        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        at.setAtMobiles(Arrays.asList(mobiles.split(",")));
        at.setIsAtAll(isAtAll != null && isAtAll);
        request.setAt(at);
        // 消息发送
        OapiRobotSendResponse response = client.execute(request);
        if (null != response && response.isSuccess()) {
            log.info("钉钉机器人发送消息成功");
        } else {
            log.error("钉钉机器人发送消息失败" + (null != response ? response.getErrmsg() : ""));
        }
    }

    public static void executeSendMessage(Boolean isAtAll, String accessToken, String message) throws Exception {
        // 客户端注册
        String dingDingTalkUrl = DING_DING_TALK_URL + accessToken;
        DingTalkClient client = new DefaultDingTalkClient(dingDingTalkUrl);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        // 属性设置
        request.setMsgtype(DING_DING_TALK_MSG_TYPE);
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(message);
        request.setText(text);
        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        at.setIsAtAll(isAtAll != null && isAtAll);
        request.setAt(at);
        // 消息发送
        OapiRobotSendResponse response = client.execute(request);
        if (null != response && response.isSuccess()) {
            log.info("钉钉机器人发送消息成功");
        } else {
            log.error("钉钉机器人发送消息失败" + (null != response ? response.getErrmsg() : ""));
        }
    }
}
